import React from 'react';
import {Button, Icon, Modal, message, Tree} from 'antd';
const TreeNode = Tree.TreeNode;
import {WeaTools, WeaLocaleProvider, WeaDialog, WeaRightMenu, WeaMoreButton} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

class E9FreqUseMenuSetting extends React.Component {
    state = {
        visible: false,
        loading: false,
        treeData: [],
        checkedKeys: [],
        halfCheckedKeys: [],
        expandedKeys: []
    };

    constructor(props) {
        super(props);
        this.getButtons = this.getButtons.bind(this);
        this.getRightMenus = this.getRightMenus.bind(this);
        this.getTreeData = this.getTreeData.bind(this);
        this.getTreeNodes = this.getTreeNodes.bind(this);
        this.onLoadData = this.onLoadData.bind(this);
        this.onExpand = this.onExpand.bind(this);
        this.onCheck = this.onCheck.bind(this);
        this.onSave = this.onSave.bind(this);
        this.onClear = this.onClear.bind(this);
        this.onSync = this.onSync.bind(this);
        this.onCancel = this.onCancel.bind(this);
    }

    render() {
        const {visible, loading, treeData, checkedKeys, expandedKeys} = this.state;

        return (
            <div onClick={this.getTreeData}>
                {this.props.children}

                <WeaDialog
                    visible={visible}
                    loading={loading}
                    title={getLabel(385807, '常用菜单设置')}
                    icon="icon-coms-portal"
                    iconBgcolor='#1a57a0'
                    buttons={this.getButtons()}
                    style={{width: 600, height: 500}}
                    hasScroll={true}
                    onCancel={this.onCancel}
                >
                    <WeaRightMenu inDialog={true} datas={this.getRightMenus()}>
                        <div style={{paddingLeft: '15px'}}>
                            <Tree checkable={true}
                                  expandedKeys={expandedKeys}
                                  checkedKeys={checkedKeys}
                                  loadData={this.onLoadData}
                                  onExpand={this.onExpand}
                                  onCheck={this.onCheck}
                            >
                                {this.getTreeNodes(treeData)}
                            </Tree>
                        </div>
                    </WeaRightMenu>
                </WeaDialog>
            </div>
        );
    }

    getButtons() {
        const {account = {}} = this.props;

        let buttons = [];
        buttons.push(<Button type="primary" onClick={this.onSave}>{getLabel(30986, '保存')}</Button>);
        buttons.push(<Button type="ghost" onClick={this.onClear}>{getLabel(15504, '清空')}</Button>);
        if (account.userid == 1) {
            buttons.push(<Button type="ghost" onClick={this.onSync}>{getLabel(19015, '同步')}</Button>);
        }
        buttons.push(<WeaMoreButton inDialog={true} datas={this.getRightMenus()}/>);
        return buttons;
    }

    getRightMenus() {
        const {account = {}} = this.props;

        let rightMenus = [];
        rightMenus.push({key: '1', icon: <i className="icon-coms-Preservation"/>, content: getLabel(30986, '保存'), onClick: this.onSave});
        rightMenus.push({key: '2', icon: <i className="icon-coms-delete"/>, content: getLabel(15504, '清空'), onClick: this.onClear});
        if (account.userid == 1) {
            rightMenus.push({key: '3', icon: <i className="icon-coms-Batch-sharing"/>, content: getLabel(19015, '同步'), onClick: this.onSync});
        }
        return rightMenus;
    }

    getTreeData() {
        this.setState({visible: true, loading: true});
        WeaTools.callApi('/api/portal/frequsemenu/treedata', 'POST', {
            parentid: 0
        }).then(data => {
            this.setState({
                loading: false,
                treeData: data.treeData,
                checkedKeys: data.checkedKeys,
                halfCheckedKeys: data.halfCheckedKeys,
                expandedKeys: data.halfCheckedKeys
            });

            const __halfCheckedKeys = [...data.halfCheckedKeys];
            for (let i = 0, len = __halfCheckedKeys.length; i < len; i++) {
                this.onLoadData({props: {eventKey: __halfCheckedKeys[i]}});
            }
        });
    }

    getTreeNodes(treeData) {
        const loop = (data) => {
            return data.map((item) => {
                const children = item.children;
                if (children && children.length) {
                    return <TreeNode key={item.id} title={item.name} isLeaf={!item.isParent}>{loop(children)}</TreeNode>;
                }
                return <TreeNode key={item.id} title={item.name} isLeaf={!item.isParent}/>;
            });
        };

        return loop(treeData);
    }

    onLoadData(treeNode) {
        const id = treeNode.props.eventKey;

        WeaTools.callApi('/api/portal/frequsemenu/treedata', 'POST', {
            parentid: id
        }).then(data => {
            let treeData = [...this.state.treeData];

            if (id == 0) {
                treeData = data.treeData;
            } else {
                const loop = (treeData) => {
                    for (let i = 0, len = treeData.length; i < len; i++) {
                        const item = treeData[i];

                        if (item.id == id) {
                            item.children = data.treeData || [];
                            break;
                        } else {
                            const children = item.children;
                            if (children && children.length) {
                                loop(children);
                            }
                        }
                    }
                };
                loop(treeData);
            }

            this.setState({
                treeData: treeData,
                checkedKeys: [...this.state.checkedKeys, ...data.checkedKeys],
                halfCheckedKeys: [...this.state.halfCheckedKeys, ...data.halfCheckedKeys],
                expandedKeys: [...this.state.expandedKeys, ...data.halfCheckedKeys]
            });

            const __halfCheckedKeys = [...data.halfCheckedKeys];
            for (let i = 0, len = __halfCheckedKeys.length; i < len; i++) {
                this.onLoadData({props: {eventKey: __halfCheckedKeys[i]}});
            }
        });
    }

    onExpand(expandedKeys) {
        this.setState({expandedKeys: expandedKeys});
    }

    onCheck(checkedKeys, e) {
        this.setState({checkedKeys: checkedKeys, halfCheckedKeys: e.halfCheckedKeys});
    }

    onSave() {
        const {checkedKeys, halfCheckedKeys} = this.state;
        const allCheckedKeys = checkedKeys.concat(halfCheckedKeys);

        WeaTools.callApi('/api/portal/frequsemenu/savefreqmenu', 'POST', {
            ids: allCheckedKeys.join(','),
        }).then((data) => {
            if (data.status == '2') {
                message.error(data.errormsg);
            } else {
                this.setState({visible: false});
                if (this.props.callback && typeof this.props.callback == 'function') {
                    this.props.callback();
                }
            }
        });
    }

    onClear() {
        Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(81491, '确定要清空常用菜单吗？'),
            onOk: () => {
                WeaTools.callApi('/api/portal/frequsemenu/savefreqmenu', 'POST', {
                    ids: ''
                }).then(data => {
                    if (data.status == '2') {
                        message.error(data.errormsg);
                    } else {
                        this.getTreeData();
                        if (this.props.callback && typeof  this.props.callback == 'function') {
                            this.props.callback();
                        }
                    }
                });
            }
        });
    }

    onSync() {
        Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(385815, '同步后所有人的常用菜单将发生变更，确定要同步吗？'),
            onOk: () => {
                const {checkedKeys, halfCheckedKeys} = this.state;
                const allCheckedKeys = checkedKeys.concat(halfCheckedKeys);

                WeaTools.callApi('/api/portal/frequsemenu/syncfreqmenu', 'POST', {
                    ids: allCheckedKeys.join(','),
                }).then((data) => {
                    if (data.status == '2') {
                        message.error(data.errormsg);
                    } else {
                        message.success(getLabel(83885, '操作成功！'));
                        if (this.props.callback && typeof  this.props.callback == 'function') {
                            this.props.callback();
                        }
                    }
                });
            }
        });
    }

    onCancel() {
        this.setState({visible: false});
    }
}

export default E9FreqUseMenuSetting;
